#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    createinterface();
}

MainWindow::~MainWindow()
{

}

void MainWindow::open()
{
    curdir = QFileDialog::getExistingDirectory(this, "Select Directory", "/home", QFileDialog::ShowDirsOnly);
    QDir dir(curdir);
    QStringList filters;
    filters << "*.txt";
    dir.setNameFilters(filters);
    QStringList files = dir.entryList(QDir::Files);
    if (!files.empty())
    {
        tbox->clear();
        tbox->addItems(files);
        tbox->setEnabled(1);
    }
}

void MainWindow::loadfile(const QString &fname)
{
    curfile = (curdir + '/' + fname);
    QFile file(curfile);
    QTextStream inpt(&file);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    textEdit->setPlainText(inpt.readAll());
}

void MainWindow::savefile()
{
    QFile file(curfile);
    if (!file.open(QFile::WriteOnly | QFile::Text))
        return;
    QTextStream out(&file);
    out << textEdit->toPlainText();
}

void MainWindow::createinterface()
{
    cwidget = new QWidget;
    clayout = new QVBoxLayout;
    toplay = new QHBoxLayout;
    botlay = new QHBoxLayout;
    textEdit = new QTextEdit;
    tbox = new QComboBox;
    tbox->setDisabled(1);
    tbutton = new QPushButton("&Open");
    botsave = new QPushButton("&Save");
    botclose = new QPushButton("&Close");
    toplay->addWidget(tbox);
    botlay->addWidget(botsave);
    botlay->addWidget(botclose);
    toplay->addWidget(tbutton);
    clayout->addLayout(toplay);
    clayout->addWidget(textEdit);
    clayout->addLayout(botlay);
    cwidget->setLayout(clayout);
    setCentralWidget(cwidget);
    connect(botclose, SIGNAL(clicked()), this, SLOT(close()));
    connect(tbutton, SIGNAL(clicked()), this , SLOT(open()));
    connect(tbox, SIGNAL(currentTextChanged(QString)), this, SLOT(loadfile(QString)));
    connect(botsave, SIGNAL(clicked()), this, SLOT(savefile()));
}
